import fp from "fastify-plugin";
import fastifyMongodb from "@fastify/mongodb";
import {
  createOrderIndexes,
  createCommentIndexes,
  createInvitationIndexes,
  createInvitedRoomIndexes,
} from "../models/schemas";

export default fp(async (fastify) => {
  fastify.register(fastifyMongodb, {
    // 强制使用新的 URL 解析器
    forceClose: true,
    url:
      process.env.MONGO_URI || "mongodb://localhost:27018/building_13-unit_2",
  });
  fastify.register(async (fastify, opts) => {
    // 确保 rooms 集合有唯一索引
    const db = fastify.mongo.db;
    if (!db) return; // 创建所有必要的索引
    await createOrderIndexes(db);
    await createCommentIndexes(db);
    await createInvitationIndexes(db);
    await createInvitedRoomIndexes(db); // 添加新索引

    await db.collection("rooms").createIndex({ orderNo: 1 }, { unique: true });
  });
});
